package com.gzxxgl.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.common.IpHelper;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.common.util.RandomUtil;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.gzxxgl.common.interceptor.LogInterceptor;
import com.gzxxgl.enu.EnumMsg;
import com.gzxxgl.model.data.SysDict;
import com.gzxxgl.model.data.User;
import com.gzxxgl.model.data.UserOrganiz;
import com.gzxxgl.util.BASE64encry;
import com.gzxxgl.util.CaptchaUtil;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;


public class CommonController extends Controller {

	@Clear
	@Before(LogInterceptor.class)
	public void index() {
		forwardAction("/goindex");
	}

	@Clear
	@Before(LogInterceptor.class)
	public void goindex() {

		if (getSessionAttr("currentuser") == null || SSOHelper.getToken(getRequest())==null) {

			render("login.jsp");

		} else {
			render("index.jsp");
		}
	}

	@Clear
	@Before(LogInterceptor.class)
	public void login() {
		setAttr("dlsjjl", "登录");

		/**
		 * 登录验证
		 */
		User u = User.dao.querybyloginName(getPara("userName"));

		if (u != null && BASE64encry.encry(getPara("password")).equals(u.getPasword())) {
			String loginName = getPara("userName");
			String pass = getPara("password");
			// 往cookie里存需要将编码方式设为UTF-8
			try {
				loginName = URLEncoder.encode(loginName, "utf-8");
				pass = URLEncoder.encode(pass, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			/*
			 * cookie设置
			 * 
			 * 一、用户选择保存帐号密码 1、用户第一次选择保存，正常保存
			 * 2、用户非第一次选择保存，说明已经有相同名字的cookie,对比帐号密码是否一致 ①一致的话不进行操作
			 * ②不一致的话重新放置cookie 二、用户选择不保存 1、如果曾经存过cookie，则清空 2、如果没有存过cookie，不用操作
			 * （直接将cookie值设为“”可以避免上面的判断，同时也可以避免获取cookie发生空指针异常）
			 */
			// 如果用户选择保存十天帐号密码，
			if (getPara("rememberMe") != null && getParaToBoolean("rememberMe")) {// 分两种情况，第一次放置cookie和不是第一次放置
				System.out.println("选择了保存账号密码");
				if (getCookieObject("loginName") == null || getCookieObject("loginPass") == null) {// 第一次放置cookie
					System.out.println("第一次放置cookie");
					setCookie("loginName", loginName, 86400);
					setCookie("loginPass", pass, 86400);
				} else {// 非第一次放置cookie
					if (!loginName.equals(getCookieObject("loginName").getValue())
							&& !pass.equals(getCookieObject("loginPass").getValue())) {// 如果帐号有变化，则重新放置cookie
						System.out.println("帐号有变化，则重新放置cookie");
						setCookie("loginName", loginName, 86400);
						setCookie("loginPass", pass, 86400);
					} // 否则，不进行操作
					else {
						System.out.println("帐号没变化，不进行操作");
					}
				}

			} else {// 没有选择保存账号密码
				System.out.println("没有选择保存账号密码");
				setCookie("loginName", "", 0);
				setCookie("loginPass", "", 0);
			}
			
			setSessionAttr("currentuser", u);
            //判断首次登陆
			if(!"0".equals(u.get("isnew"))){
	
				render("index.jsp");
			
			}else{
				//修改密码
				render("editpassword.jsp");
			}
		
		} else {

			setAttr("msg", EnumMsg.ERR);
			render("login.jsp");
		}

	}
	@Clear
	@Before(LogInterceptor.class)
	public void loginkis() {
		SSOToken mt = SSOHelper.getToken(getRequest());
		if ( mt != null && getSessionAttr("currentuser") != null) {
			redirect("/goindex");
			return;
		}
		/**
		 * 登录 生产环境需要过滤sql注入
		 */
		if ( HttpUtil.isPost(getRequest()) ) {
			WafRequestWrapper req = new WafRequestWrapper(getRequest());
			String username = req.getParameter("userName");
			String password = req.getParameter("password");
			User u = User.dao.querybyloginName(username);

			if (u != null && BASE64encry.encry(password).equals(u.getPasword())) {
				/**
				 * 系统定义 SSOToken st = new SSOToken();
				 * <p>
				 * 自定义 MyToken
				 * </p>
				 */
				mt = new SSOToken();
				mt.setId(u.getGid());
				mt.setUid(RandomUtil.get32UUID());
				mt.setObject(u);
				mt.setIp(IpHelper.getIpAddr(getRequest()));
				
				//记住密码，设置 cookie 时长 1 周 = 604800 秒 【动态设置 maxAge 实现记住密码功能】
				String rememberMe = req.getParameter("rememberMe");
				if ( rememberMe != null && getParaToBoolean("rememberMe") ) {
					getRequest().setAttribute(SSOConfig.SSO_COOKIE_MAXAGE, 604800); 
				}
				
				SSOHelper.setSSOCookie(getRequest(), getResponse(), mt, true);
				System.out.println("=============================="+SSOHelper.getLoginCount(getRequest()));
				setSessionAttr("currentuser", u);
	            //判断首次登陆
				if(!"0".equals(u.get("isnew"))){
		
					redirect("/goindex");
					return;
				
				}else{
					//修改密码
					render("editpassword.jsp");
				}
			}
		}
		render("login.jsp");
	}
	@Clear
	@Before(LogInterceptor.class)
	public void logout() {

		/**
		 * <p>
		 * SSO 退出，清空退出状态即可
		 * </p>
		 * 
		 * <p>
		 * 子系统退出 SSOHelper.logout(request, response); 注意 sso.properties 包含 退出到
		 * SSO 的地址 ， 属性 sso.logout.url 的配置
		 * </p>
		 */
		SSOHelper.clearLogin(getRequest(), getResponse());
		getSession().invalidate();

		render("login.jsp");
	}

	/**
	 * 查字典
	 */
	public void selectdect() {
		setAttr("dlsjjl", "查字典");
		Map<String, Object> m = new HashMap<>();
		m.put("flag", false);
		m.put("msg", EnumMsg.ERR);

		List<SysDict> S = SysDict.dao.query();

		if (S.size() > 0) {
			m.put("flag", true);
			m.put("msg", EnumMsg.SUCCESS);
			m.put("list", S);
		}

		renderJson(m);
	}

	/**
	 * 文件上传接口
	 */
	public void _upload() {
		setAttr("dlsjjl", "上传文件 ");
		Map<String, Object> json = new HashMap<>();
		Map<String, Object> data = new HashMap<>();

		String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss").format(new Date());
		UploadFile file = getFile("file");
		File source = file.getFile();
		String fileName = file.getFileName();

		json.put("filename", fileName);

		String extension = fileName.substring(fileName.lastIndexOf("."));
		String prefix;
		if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)) {
			prefix = "img";
			fileName = generateWord() + extension;
		} else {
			prefix = "file";
		}

		try {
			FileInputStream fis = new FileInputStream(source);
			File targetDir = new File(PathKit.getWebRootPath() + "/" + prefix + "/u/" + path);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
			File target = new File(targetDir, fileName);
			if (!target.exists()) {
				target.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(target);
			byte[] bts = new byte[300];
			while (fis.read(bts, 0, 300) != -1) {
				fos.write(bts, 0, 300);
			}
			fos.close();
			fis.close();
			json.put("isSuccess", true);
			json.put("code", 0);
			json.put("url", prefix + "/u/" + path + "/" + fileName);
			data.put("src", prefix + "/u/" + path + "/" + fileName);
			json.put("data", data);
			source.delete();

		} catch (FileNotFoundException e) {
			json.put("isSuccess", false);
			json.put("code", 1);
			json.put("msg", "上传出现错误，请稍后再上传");
		} catch (IOException e) {
			json.put("isSuccess", false);
			json.put("code", 1);
			json.put("msg", "文件写入服务器出现错误，请稍后再上传");
		}

		// getResponse().setContentType("application/json;charset=UTF-8");
		// renderJson(json);
		render(new JsonRender(json).forIE());
	}

	/**
	 * 文件下载
	 */
	public void _download() {
		setAttr("dlsjjl", "下载文件");
		String path = PathKit.getWebRootPath() + "/" + getPara("url");

		renderFile(path);
	}

	// 生成文件名
	private String generateWord() {
		String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
				"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
		List<String> list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(5, 9);
		return result;
	}

	public void avgsex() {
		setAttr("dlsjjl", "查看性别统计");
		Map<String, Object> m = new HashMap<>();
		m.put("flag", false);
		m.put("msg", EnumMsg.ERR);

		List<Record> lr = Db.find(
				" select o.oname, count(infoid) as num from g_user_organiz o left join (select * from g_user_info t where t.isdelete=0 and t.xb = '男') y on o.BMBH = y.szbmid where o.levl='B' group by o.oname, o.organizid order by o.organizid ");
		List<Record> lrn = Db.find(
				" select o.oname, count(infoid) as num from g_user_organiz o left join (select * from g_user_info t where t.isdelete=0 and t.xb = '女') y on o.BMBH = y.szbmid where o.levl='B' group by o.oname, o.organizid order by o.organizid ");
		List<UserOrganiz> l = UserOrganiz.dao.querylevl("B");

		String[] s = new String[l.size()];
		int[] v1 = new int[lr.size()], v2 = new int[lrn.size()];
		for (Integer i = 0, length = l.size(); i < length; i++) {
			s[i] = l.get(i).getOname();
			v1[i] = lr.get(i).getBigDecimal("num").intValue();
			v2[i] = lrn.get(i).getBigDecimal("num").intValue();
		}
	
			m.put("flag", true);
			m.put("msg", EnumMsg.SUCCESS);
			m.put("xAxis", s);
			m.put("sdata1", v1);
			m.put("sdata2", v2);

		renderJson(m);
	}

	public void avgage() {
		setAttr("dlsjjl", "查看年龄统计");
		Map<String, Object> m = new HashMap<>();
		m.put("flag", false);
		m.put("msg", EnumMsg.ERR);

		List<Record> lr = Db.find(
				" select o.oname, avg(t.gage) as num from g_user_organiz o left join g_user_info t on o.BMBH = t.szbmid where  o.levl='B' group by o.oname, o.organizid order by o.organizid ");
		List<UserOrganiz> l = UserOrganiz.dao.querylevl("B");

		String[] s = new String[l.size()];
		int[] v1 = new int[lr.size()];
		for (Integer i = 0, length = l.size(); i < length; i++) {
			s[i] = l.get(i).getOname();

			v1[i] = StrKit.notBlank(lr.get(i).getBigDecimal("num") + "") ? lr.get(i).getBigDecimal("num").intValue() : 0;
		}
		if (s != null && v1 != null) {
			m.put("flag", true);
			m.put("msg", EnumMsg.SUCCESS);
			m.put("xAxis", s);
			m.put("sdata1", v1);
		}

		renderJson(m);
	}
	public void verif(){
		/**
		 * 验证码
		 */
			HttpServletResponse response = getResponse();
			try {
				String verifyCode = CaptchaUtil.outputImage(response.getOutputStream());
				System.out.println("验证码:" + verifyCode);
			} catch (IOException e) {
				e.printStackTrace();
			}
			renderNull();
	}
	
	public void button() {
		render("button.html");
	}

	public void organiz() {
		setAttr("dlsjjl", "查看组织关系");
		render("organiz.jsp");
	}

	public void userinfo() {
		setAttr("dlsjjl", "查看用户信息");
		render("userinfo.jsp");
	}

	public void salary() {
		setAttr("dlsjjl", "查看工资信息");
		render("salary.jsp");
	}

	public void salarydata() {
		setAttr("dlsjjl", "查看工资统计");
		render("salarydata.jsp");
	}

	public void userself() {
		setAttr("dlsjjl", "查看个人 信息");
		render("userself.jsp");
	}

	public void logs() {
		setAttr("dlsjjl", "查看日志信息");
		render("logs.jsp");
	}

	public void userinfoapprove() {
		setAttr("dlsjjl", "个人信息修改审批");
		render("userinfoapprove.jsp");
	}

}
